var pjs = globalThis.pjs;
var fs = pjs.py_import("native_fs");
var utils = fs.py_import("utils");

console.log(utils.random_string(16))

function setDescriptor(instance) {
    if (globalThis.descriptors == undefined) {
        globalThis.descriptors = {
            index: 0,
            instances: []
        }
    }
    globalThis.descriptors.instances[globalThis.descriptors.index] = instance;
    return globalThis.descriptors.index++;
}

function getDescriptor(idx) {
    if (idx >= globalThis.descriptors.instances.length) throw new Error("idx rather than instances length");
    return globalThis.descriptors.instances[idx];
}

function open(filePath, flags) {
    flags = flags.replace("b", "");
    var ins = {
        path: filePath,
        flags: flags
    };
    var fd = setDescriptor(ins);
    return fd;
}

function size(fd) {
    var size = -1;
    var instance = getDescriptor(fd);
    if (instance) {
        size = pjs.size(instance.path);
    }
    return size;
}

function close(fd) {
    var instance = getDescriptor(fd);
    fs.closeSync(fd);
    return undefined;
}

function exists(filePath) {
    console.log(123123)
    var result = false;
    filePath = checkPath(filePath);
    try {
        result = fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
        // console.log('can read/write');
        console.log(11111, result)
        result = true;
    } catch (err) {
        result = false;
        // console.error('no access!');
    }
    // var result = fs.accessSync(filePath);
    // var reult = fs.statSync(filePath);
    return result ? 1: -1;
}

function read(fd, buffer, size) {
    return fs.readSync(fd, buffer, { offset: 0, length: size, position: 0 });
}

function rename(oldPath, newPath) {
    return fs.renameSync(oldPath, newPath);
}

function remove(filePath) {
    return fs.rmSync(filePath, { force: false, maxRetries: 3, recursive: true, retryDelay: 200 })
}

function write(fd, buffers, size) {
    return fs.writeSync(fd, buffers, 0, size, 0);
}